package related

import (
	"fmt"

	"github.com/jinzhu/gorm"
)

// type User1 struct {
// 	Id   int
// 	Name string
// 	Age  int
// 	Addr string
// }

// type GradeInfo struct {
// 	Grade int
// 	Class int
// 	User  User1 `form:"ForeignKey:UId;AssociationForeignkey:Id"`
// 	UId   int
// }

type User1 struct {
	Id   int
	Name string
	Age  int
	Addr string
	UId  int //外键
}

type GradeInfo struct {
	Id    int
	Grade int
	Class int
	User  User1 `gorm:"ForeignKey:UId;AssociationForeignkey:Id"` //关联信息
}

func CreateOneToOne(db *gorm.DB) {
	//创建one_to_one
	grainfo := GradeInfo{Grade: 1, Class: 2, User: User1{Name: "xiaoming", Age: 11, Addr: "湖北省"}}
	db.Create(&grainfo)
}

func QueryOneToOne(db *gorm.DB) {
	//创建one_to_one
	var GradeInfo1 GradeInfo
	db.First(&GradeInfo1, 1)
	fmt.Print(GradeInfo1)

	db.Model(&GradeInfo1).Association("User").Find(&GradeInfo1.User)
	fmt.Printf("第一种查询方式:%v\n", GradeInfo1)

	//第二种查询方式
	var GradeInfo2 GradeInfo
	db.Preload("User").First(&GradeInfo2, 1)
	fmt.Printf("第二种查询方式:%v\n", GradeInfo2)

	//第三种查询方式
	var GradeInfo3 GradeInfo
	db.First(&GradeInfo3, 1)

	var user1 User1
	db.Model(&GradeInfo3).Related(&user1, "User")

	fmt.Printf("第三种查询方式:%v\n", GradeInfo3)

}

func UpdateOneToOne(db *gorm.DB) {
	//创建one_to_one
	var GradeInfo1 GradeInfo
	db.Preload("User").First(&GradeInfo1, 1)

	db.Model(&GradeInfo1.User).Update("Name", "xiaoming")
	fmt.Println(GradeInfo1)
}

func DelOneToOne(db *gorm.DB) {
	//创建one_to_one
	var GradeInfo1 GradeInfo
	db.Preload("User").First(&GradeInfo1, 1)
	fmt.Println(GradeInfo1)

	db.Debug().Delete(&GradeInfo1.User)
	// fmt.Println(GradeInfo1)
}
